﻿using System;
using System.Linq;
using System.Windows;
using TheGameClient.Webservices;
using Waaahsabi.Controls.FileSystem;

namespace TheGameClient
{
    public partial class DlgBrowseLocalFile
    {
		public GatewayFileItem FileItem { get; private set; }
		public string FileFilter { get; set; }
        public DlgBrowseLocalFile(string filter = null)
        {
            InitializeComponent();
			if (!string.IsNullOrEmpty(filter))
				FileFilter = filter;
        	fileMgr.IsCondensed = true;
			App.Client.GetFilesInDirectoryCompleted += ClientGetFilesInDirectoryCompleted;
			App.Client.GetFilesInDirectoryAsync(App.InternalSessionId, App.MyRootDirectoryId);
        }

		void ClientGetFilesInDirectoryCompleted(object sender, GetFilesInDirectoryCompletedEventArgs e)
		{
			App.Client.GetFilesInDirectoryCompleted -= ClientGetFilesInDirectoryCompleted;
			if (e.Error != null) { App.ServerError(); return; }
			if (e.Result != null)
			{
				var fileItems = from item in e.Result
				                select new GatewayFileItem
				                {
				                	FileName = item.Name,
				                	FileId = item.Id,
				                	FileSize = item.DisplaySize,
				                	FileCompressionLevel = item.CompressionLevel,
				                	FileEncryptionLevel = item.EncryptionLevel,
				                	FileVersion = (item is ProgramFile) ? ((ProgramFile) item).Version : 0,
								};
				foreach (var item in fileItems)
				{
					item.Click += FileItemClicked;
					fileMgr.FileItems.Add(item);
				}
				fileMgr.Filter = FileFilter;
				fileMgr.SetCondensed();
			}
		}

		void FileItemClicked(object sender, EventArgs e)
		{
			GatewayFileItem gfi = sender as GatewayFileItem;
			if (gfi == null)
				return;
			txtFileName.DataContext = gfi;
		}

        private void OkButtonClick(object sender, RoutedEventArgs e)
        {
        	FileItem = txtFileName.DataContext as GatewayFileItem;
            DialogResult = true;
        }

        private void CancelButtonClick(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }
    }
}

